{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting ../data/mnist/input_data/train-images-idx3-ubyte.gz\n",
      "Extracting ../data/mnist/input_data/train-labels-idx1-ubyte.gz\n",
      "Extracting ../data/mnist/input_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting ../data/mnist/input_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From <ipython-input-1-9a202c359357>:92: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See tf.nn.softmax_cross_entropy_with_logits_v2.\n",
      "\n",
      "step 100, entropy loss: 0.396959, l2_loss: 295.127869, total loss: 0.408764\n",
      "0.9288\n",
      "step 200, entropy loss: 0.132904, l2_loss: 409.175201, total loss: 0.149271\n",
      "0.9458\n",
      "step 300, entropy loss: 0.162602, l2_loss: 497.390198, total loss: 0.182498\n",
      "0.9579\n",
      "step 400, entropy loss: 0.221780, l2_loss: 597.611084, total loss: 0.245685\n",
      "0.9572\n",
      "step 500, entropy loss: 0.221074, l2_loss: 663.475952, total loss: 0.247613\n",
      "0.9579\n",
      "step 600, entropy loss: 0.208156, l2_loss: 760.490784, total loss: 0.238575\n",
      "0.9456\n",
      "step 700, entropy loss: 0.032754, l2_loss: 760.201599, total loss: 0.063162\n",
      "0.9676\n",
      "step 800, entropy loss: 0.069093, l2_loss: 752.077332, total loss: 0.099176\n",
      "0.9717\n",
      "step 900, entropy loss: 0.022698, l2_loss: 752.175720, total loss: 0.052785\n",
      "0.9698\n",
      "step 1000, entropy loss: 0.053509, l2_loss: 753.823120, total loss: 0.083662\n",
      "0.9702\n",
      "step 1100, entropy loss: 0.040610, l2_loss: 761.701843, total loss: 0.071078\n",
      "0.9742\n",
      "step 1200, entropy loss: 0.061603, l2_loss: 760.437012, total loss: 0.092020\n",
      "0.9744\n",
      "step 1300, entropy loss: 0.033363, l2_loss: 748.588074, total loss: 0.063307\n",
      "0.9769\n",
      "step 1400, entropy loss: 0.130997, l2_loss: 737.845886, total loss: 0.160511\n",
      "0.979\n",
      "step 1500, entropy loss: 0.069933, l2_loss: 730.380371, total loss: 0.099148\n",
      "0.9768\n",
      "step 1600, entropy loss: 0.045966, l2_loss: 723.252930, total loss: 0.074896\n",
      "0.975\n",
      "step 1700, entropy loss: 0.031310, l2_loss: 712.619812, total loss: 0.059815\n",
      "0.9785\n",
      "step 1800, entropy loss: 0.026142, l2_loss: 704.715820, total loss: 0.054331\n",
      "0.9778\n",
      "step 1900, entropy loss: 0.034067, l2_loss: 696.897583, total loss: 0.061943\n",
      "0.9804\n",
      "step 2000, entropy loss: 0.062383, l2_loss: 689.342651, total loss: 0.089956\n",
      "0.98\n",
      "step 2100, entropy loss: 0.096468, l2_loss: 681.885315, total loss: 0.123744\n",
      "0.9805\n",
      "step 2200, entropy loss: 0.008895, l2_loss: 676.262024, total loss: 0.035945\n",
      "0.9786\n",
      "step 2300, entropy loss: 0.032221, l2_loss: 668.342712, total loss: 0.058954\n",
      "0.98\n",
      "step 2400, entropy loss: 0.002693, l2_loss: 661.060669, total loss: 0.029135\n",
      "0.9802\n",
      "step 2500, entropy loss: 0.028558, l2_loss: 655.921875, total loss: 0.054795\n",
      "0.9806\n",
      "step 2600, entropy loss: 0.027502, l2_loss: 651.353455, total loss: 0.053556\n",
      "0.98\n",
      "step 2700, entropy loss: 0.014592, l2_loss: 646.718811, total loss: 0.040461\n",
      "0.9803\n",
      "step 2800, entropy loss: 0.026629, l2_loss: 641.817505, total loss: 0.052301\n",
      "0.9811\n",
      "step 2900, entropy loss: 0.006144, l2_loss: 636.551392, total loss: 0.031606\n",
      "0.9805\n",
      "step 3000, entropy loss: 0.010974, l2_loss: 632.086548, total loss: 0.036257\n",
      "0.9817\n"
     ]
    }
   ],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "import numpy as np\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None\n",
    "\n",
    "def swish(x):\n",
    "  return x * tf.nn.sigmoid(x)\n",
    "\n",
    "\n",
    "def selu(x):\n",
    "  with tf.name_scope('elu') as scope:\n",
    "    alpha = 1.6732632423543772848170429916717\n",
    "    scale = 1.0507009873554804934193349852946\n",
    "    return scale*tf.where(x>=0.0, x, alpha*tf.nn.elu(x))\n",
    "\n",
    "def relu(x):\n",
    "    return tf.nn.relu(x)\n",
    "\n",
    "def activation(x):\n",
    "  return swish(x)\n",
    "\n",
    "def initialize(shape, stddev=0.1):\n",
    "  return tf.truncated_normal(shape, stddev=stddev)\n",
    "\n",
    "\n",
    "data_dir = '../data/mnist/input_data/'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "\n",
    "init_learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "# Create the model\n",
    "L1_units_count = 100\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "epoch_steps = tf.to_int64(tf.div(60000, tf.shape(x)[0]))\n",
    "global_step = tf.train.get_or_create_global_step()\n",
    "current_epoch = global_step//epoch_steps\n",
    "decay_times = current_epoch \n",
    "current_learning_rate = tf.multiply(init_learning_rate, \n",
    "                                    tf.pow(0.575, tf.to_float(decay_times)))\n",
    "\n",
    "W_1 = tf.Variable(initialize([784, L1_units_count], \n",
    "                             stddev=np.sqrt(2/784)))\n",
    "b_1 = tf.Variable(tf.constant(0.001, shape=[L1_units_count]))\n",
    "logits_1 = tf.matmul(x, W_1) + b_1\n",
    "output_1 = activation(logits_1)\n",
    "\n",
    "L2_units_count = 10 \n",
    "W_2 = tf.Variable(initialize([L1_units_count, \n",
    "                              L2_units_count], \n",
    "                             stddev=np.sqrt(2/L1_units_count)))\n",
    "b_2 = tf.Variable(tf.constant(0.001, shape=[L2_units_count]))\n",
    "logits_2 = tf.matmul(output_1, W_2) + b_2  \n",
    "\n",
    "y = logits_2\n",
    "\n",
    "\n",
    "\n",
    "# 损失函数\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])\n",
    "\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n",
    "l2_loss = tf.nn.l2_loss(W_1) + tf.nn.l2_loss(W_2)\n",
    "total_loss = cross_entropy + 4e-5*l2_loss\n",
    "\n",
    "optimizer = tf.train.AdamOptimizer(current_learning_rate)\n",
    "gradients = optimizer.compute_gradients(total_loss)\n",
    "train_step = optimizer.apply_gradients(gradients)\n",
    "\n",
    "train_step = tf.train.AdamOptimizer(current_learning_rate).minimize(total_loss, global_step=global_step)\n",
    "\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "sess = tf.InteractiveSession()\n",
    "tf.global_variables_initializer().run()\n",
    "\n",
    "# 开始训练\n",
    "for step in range(3000):\n",
    "  batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "  lr = 1e-2\n",
    "  _, loss, l2_loss_value, total_loss_value, current_lr_value = \\\n",
    "      sess.run([train_step,cross_entropy,l2_loss,total_loss, current_learning_rate], \n",
    "                feed_dict={x: batch_xs, y_: batch_ys, init_learning_rate:lr})\n",
    "  \n",
    "  if (step+1) % 100 == 0:\n",
    "    print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % (step+1, loss, l2_loss_value, total_loss_value))\n",
    "    print(sess.run(accuracy, feed_dict={x: mnist.test.images,y_: mnist.test.labels}))\n",
    "    "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
